package org.realogic.cfm.persistence.dialect.db;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.session.Configuration;
import org.realogic.cfm.persistence.KParameter;
import org.realogic.cfm.persistence.dialect.AbstractDialect;
import org.realogic.cfm.persistence.query.QueryCondition;

/**
 * DB2的分页数据库方言实现
 */
public class DB2Dialect extends AbstractDialect {

	public boolean supportsLimit() {
		return true;
	}

	private static String getRowNumber(String sql) {
		StringBuilder rownumber = new StringBuilder(50).append("rownumber() over(");
		int orderByIndex = sql.toLowerCase().indexOf("order by");
		if (orderByIndex > 0 && !hasDistinct(sql)) {
			rownumber.append(sql.substring(orderByIndex));
		}
		rownumber.append(") as rownumber_,");
		return rownumber.toString();
	}

	private static boolean hasDistinct(String sql) {
		return sql.toLowerCase().contains("select distinct");
	}

	@Override
	public String getLimitString(String sql, int offset, int limit) {
		return getLimitString(sql);
	}

	/**
	 * 将sql变成分页sql语句,提供将offset及limit使用占位符号(placeholder)替换.
	 * 
	 * <pre>
	 * 如mysql
	 * dialect.getLimitString("select * from user", 12, ":offset",0,":limit") 将返回
	 * select * from user limit :offset,:limit
	 * </pre>
	 * 
	 * @param sql
	 *            实际SQL语句
	 * @param offset
	 *            分页开始纪录条数
	 * @param offsetPlaceholder
	 *            分页开始纪录条数－占位符号
	 * @param limitPlaceholder
	 *            分页纪录条数占位符号
	 * @return 包含占位符的分页sql
	 */
	public String getLimitString(String sql) {
		int startOfSelect = sql.toLowerCase().indexOf("select");
		StringBuilder pagingSelect = new StringBuilder(sql.length() + 100).append(sql.substring(0, startOfSelect)).append("select * from ( select ").append(getRowNumber(sql));
		if (hasDistinct(sql)) {
			pagingSelect.append(" row_.* from ( ").append(sql.substring(startOfSelect)).append(" ) as row_");
		} else {
			pagingSelect.append(sql.substring(startOfSelect + 6));
		}
		pagingSelect.append(" ) as temp_ where rownumber_ ");
		pagingSelect.append("between ? and ?");
		return pagingSelect.toString();
	}

	public List<ParameterMapping> newParameterMappings(MappedStatement mappedStatement, BoundSql boundSql, QueryCondition queryCondition, boolean isPaging) {
		List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
		Configuration configuration = mappedStatement.getConfiguration();
		ParameterMapping.Builder builder = null;
		List<KParameter> tmpParamList = queryCondition.getParameterList();
		int size = tmpParamList == null ? 0 : tmpParamList.size();
		KParameter tmpParam = null;
		for (int i = 0; i < size; i++) {
			tmpParam = tmpParamList.get(i);
			builder = new ParameterMapping.Builder(configuration, tmpParam.getName(), tmpParam.geClassClass());
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter(tmpParam.getName(), tmpParam.getValueValue());
		}
		// 分页
		if (isPaging && queryCondition.isDisplayByPage()) {
			int pageSize = queryCondition.getPageSize();
			int index = (queryCondition.getPageNo() - 1) * pageSize;
			int start = index < 0 ? 0 : index;
			int end = index + pageSize;
			builder = new ParameterMapping.Builder(configuration, "_start_", Integer.class);
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter("_start_", start+1);
			builder = new ParameterMapping.Builder(configuration, "_end_", Integer.class);
			newParameterMappings.add(builder.build());
			boundSql.setAdditionalParameter("_end_", end);
		}
		return newParameterMappings;
	}
}
